package com.hmall.order.task;

import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 自定义定时任务，实现订单状态定时处理
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "0 * * * * *")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单：{}", new Date());

        LocalDateTime time = LocalDateTime.now().minus(Duration.ofMinutes(30));
        Date orderTime = Date.from(time.atZone(ZoneId.systemDefault()).toInstant());

        // select * from tb_order where status = 1 and create_time < 当前时间-1分钟
        List<Order> ordersList = orderMapper.getByStatusAndOrderTime(1, orderTime);
        if(ordersList != null && !ordersList.isEmpty()){
            ordersList.forEach(order -> {
                order.setStatus(5);
                order.setCloseTime(new Date());
                orderMapper.updateById(order);
            });
            log.info("已处理超时订单数量：{}", ordersList.size());
        }else {
            log.info("没有超时的未支付订单需要处理");
        }
    }
    //若未支付归还库存

    @PostConstruct
    public void init() {
        // 在应用启动时立即执行一次定时任务
        processTimeoutOrder();
    }

}